#include "CVlcSocket.h"
#include <stdlib.h>


#ifdef WIN_32
#pragma comment(lib, "Ws2_32.lib")
#elif defined LINUX

#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <netinet/in.h>          
#include <arpa/inet.h>
#endif

/* c'tor - creates a connection via socket with the requested IP adress and port number */
CVlcSocket::CVlcSocket(std::string sIP, int port)
{
#ifdef WIN_32
	static bool bFirstTime = true;
	if (bFirstTime){
		bFirstTime = false;
		WSAData data;
		WSAStartup( MAKEWORD( 2, 2 ), &data );
	}

	//create a windows socket
	sockaddr_in dest;
	dest.sin_family = AF_INET;
	dest.sin_addr.s_addr = inet_addr( sIP.c_str() );
	dest.sin_port = htons(port);

	m_socket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
	if (m_socket < 0){
		int err = WSAGetLastError();
		printf("_createSocket:: create socket err msg: %d\n", err);
		exit(-1);
	}
	if (connect(m_socket, (struct sockaddr *) &dest, sizeof(dest))<0)
	{
		int err = WSAGetLastError();
		printf("_createSocket:: connect socket err msg: %d\n", err);
		exit(-1);
	}
#elif defined LINUX
	//create a windows socket
	sockaddr_in dest;
	dest.sin_family = AF_INET;
	dest.sin_addr.s_addr = inet_addr( sIP.c_str() );
	dest.sin_port = htons(port);

	m_socket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
	if (m_socket < 0){
		printf("_createSocket:: create socket err msg:\n");
		exit(-1);
	}
	if (connect(m_socket, (struct sockaddr *) &dest, sizeof(dest))<0)
	{
		printf("_createSocket:: connect socket err msg: \n");
		exit(-1);
	}
#endif
}
CVlcSocket::~CVlcSocket(void)
{
#ifdef WIN_32
	closesocket(m_socket);
	static bool bFirstTime = true;
	if (bFirstTime){
		bFirstTime = false;
		WSACleanup();
	}
#elif defined LINUX
	close(m_socket);
#endif
}



void CVlcSocket::sendPacket(const char* cBuffer, int nSize)
{
	int res = send(m_socket, cBuffer, nSize, 0);
#ifdef WIN_32
	if (res != nSize)
	{
		int err = WSAGetLastError();
		printf("err msg: %d", err);
		exit(-1);
	}
#elif defined LINUX
	if (res < 0) 
	{
		printf("error writing to socket: %d \n", res);
		//exit(-1);
	}
#endif
}
